/*******************************************************************************
 * Developer: Ian Doyle
 * Date:      6/23/2012
 *
 * All code Copyright (C) 2012 Ian Doyle. All rights reserved.
 *
 * This file is a part of FileFocus.
 *
 * FileFocus is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * FileFocus is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with FileFocus.  If not, see <http://www.gnu.org/licenses/>.
 ******************************************************************************/


package filefocus;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import filefocus.exception.UnreadableFileException;

public class MD5FileDigester implements FileDigester{
	
	private final int chunkSize;
	private final MessageDigest hash; 
	
	public MD5FileDigester(int processingChunkSize) throws NoSuchAlgorithmException
	{
		hash = MessageDigest.getInstance("MD5");
		chunkSize = processingChunkSize;
	}
	
	public synchronized byte[] digestFile(File fin) throws FileNotFoundException, IOException, UnreadableFileException 
	{
		if(!fin.isFile())
		{
			throw new FileNotFoundException(fin.getCanonicalPath() + " does not exist!");
		}
		
		boolean readable = fin.canRead();
		if(!readable)
		{
			if(!fin.setReadable(true))
			{
				throw new UnreadableFileException(fin.getCanonicalPath() + " is not readable and cannot be set to readable!");
			}
		}
		
		long fileLength = fin.length();
		FileInputStream fins;
		byte[] data = new byte[chunkSize];
		int bytesRead = 0;
		long bytesDigested = 0;
		
		try {
			fins = new FileInputStream(fin);
		}
		catch(IOException e)
		{
			if(!readable)
			{
				fin.setReadable(false);
			}
			throw e;
		}		
		
		while(bytesDigested < fileLength)
		{
			try {
				bytesRead = fins.read(data);
			}
			catch(IOException e)
			{
				if(!readable)
				{
					fin.setReadable(false);
				}
				throw e;
			}
			
			if(bytesRead > 0)
			{
				hash.update(data, 0, bytesRead);
				bytesDigested += bytesRead;
			}
		}
		
		if(!readable)
		{
			fin.setReadable(false);
		}
		
		byte[] md5sum = hash.digest();
		
		hash.reset();
		
		return md5sum;
	}
	
}
